/*
 * Copyright (c) 2023, LXMS (lxinet.cn).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.lxinet.lxms.framework.security.evaluator;

import cn.lxinet.lxms.framework.security.entity.LxmsUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 权限校验
 *
 * @author zcx
 * @date 2023/07/19
 */
@Component("lxp")
public class LxmsPermissionEvaluator {

    public boolean hasPermission(String... perms) {
        Set<String> permissions = new HashSet();
        LxmsUser lxmsUser = (LxmsUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (lxmsUser.isAdministrator()){
            return true;
        }
        Collection<? extends GrantedAuthority> grantedAuthorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        grantedAuthorities.forEach(auth -> permissions.add(auth.getAuthority()));
        for (String perm : perms){
            if (permissions.contains(perm)) {
                return true;
            }
        }
        return false;
    }

}
